<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\admin;

use App\Model\Admin\Dict;
use App\Model\Admin\Option;
use Psr\Http\Message\ResponseInterface;

/**
 * 字典管理.
 */

class DictController extends Base
{
    /**
     * 不需要授权的方法.
     */
    protected array $noNeedAuth = ['get'];

    /**
     * 浏览.
     */
    public function index(): ResponseInterface
    {
        $render = $this->render;
        return $render->render('dict/index');
    }

    /**
     * 查询.
     */
    public function select(): ResponseInterface
    {
        $request = $this->request;
        $name = $request->input('name', '');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $offset = ($page - 1) * $limit;
        if ($name && is_string($name)) {
            $items = Option::where('name', 'like', "dict_{$name}%")->limit($limit)->offset($offset)->get()->toArray();
        } else {
            $items = Option::where('name', 'like', 'dict_%')->limit($limit)->offset($offset)->get()->toArray();
        }
        $get_items = Option::where('name', 'like', "dict_{$name}%")->get()->toArray();
        $count = count($get_items);
        foreach ($items as &$item) {
            $item['name'] = Dict::optionNameTodictName($item['name']);
        }
        return $this->json(0, 'ok', $items, $count);
    }

    /**
     * 插入.
     */
    public function insert(): ResponseInterface
    {
        $request = $this->request;
        $render = $this->render;
        if ($request->isMethod('post')) {
            $name = $request->post('name');
            if (Dict::get($name)) {
                return $this->json(1, '字典已经存在');
            }
            $values = (array) $request->post('value', []);
            Dict::save($name, $values);
        }
        return $render->render('dict/insert');
    }

    /**
     * 更新.
     */
    public function update(): ResponseInterface
    {
        $request = $this->request;
        $render = $this->render;
        if ($request->isMethod('post')) {
            $name = $request->post('name');
            if (! Dict::get($name)) {
                return $this->json(1, '字典不存在');
            }
            Dict::save($name, $request->post('value'));
        }
        return $render->render('dict/update');
    }

    /**
     * 删除.
     */
    public function delete(): ResponseInterface
    {
        $request = $this->request;
        $render = $this->render;
        $names = (array) $request->post('name');
        Dict::delete($names);
        return $this->json(0);
    }

    /**
     * 获取.
     */
    public function get($name): ResponseInterface
    {
        return $this->json(0, 'ok', (array) Dict::get($name));
    }
}
